/**
 * App router config
 */
import Vue from 'vue'
import VueRouter from 'vue-router'

import moduleRoutes from './modules'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: (resolve) => {
      require(['@/views/Login.vue'], resolve)
    },
    meta: {
      skipAuth: true
    }
  },
  {
    // admin router
    path: '/m2',
    component: (resolve) => {
      require(['@/views/CommonView.vue'], resolve)
    },
    children: [...moduleRoutes, {
      path: '/', redirect: '/m2/dashboard'
    }]
  },
  {
    path: '/', redirect: '/m2'
  },
  {
    path: '*',
    component: {
      render(h) {
        return h('div', { attrs: { style: 'display:flex;justify-content:center;width:100%;font-size:32px' } }, 'Page not found')
      }
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  linkActiveClass: 'active',
  scrollBehavior: () => ({ y: 0 }),
  routes
})


export function hook (store) {
  // router
  router.beforeEach((to, from, next) => {
    const userPromise = store.dispatch('initUserInfo')

    // 确保用户身份信息已获取
    if (!to.meta.skipAuth) {
      userPromise.then(() => {
        next()
      }).catch(err => {
        console.error(err)
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      })
    } else {
      next()
    }
  })

  router.afterEach(() => {
    // store.dispatch('changeRouteLoading', false)

  })
}

export default router
